package weixin

import (
	"context"
	"errors"
	"fmt"
	"regexp"
	"time"

	"gitee.com/shoyer/logger"
	"gitee.com/shoyer/util/http"
)

type Error struct {
	ErrCode int    `json:"errcode,omitempty"`
	ErrMsg  string `json:"errmsg,omitempty"`
}

func Get(path string, res interface{}, options *http.Options) (err error) {
	return request(http.GET, path, res, options)
}

func Post(path string, res interface{}, options *http.Options) (err error) {
	return request(http.POST, path, res, options)
}

func request(typ, path string, res interface{}, options *http.Options) (err error) {
	for i := 0; i < 3; i++ {
		switch typ {
		case http.GET:
			err = http.GetJson(getEntry()+path, res, options)
		case http.POST:
			err = http.PostJson(getEntry()+path, res, options)
		default:
			err = fmt.Errorf("method not supported, %s", typ)
			return
		}

		if err == nil {
			break
		}

		// 错误处理，重试
		if IsTimeoutErr(err) {
			logger.Printf(path)
			logger.Infof("请求超时，重试中 %d, error = %s", i, err.Error())
			time.Sleep(time.Second)
			continue
		} else {
			return
		}
	}

	return
}

func getEntry() string {
	return "https://qyapi.weixin.qq.com"
}

func IsTimeoutErr(err error) bool {
	r, er := regexp.Compile("(?i)timeout")
	logger.ErrorfIfNotNil(er)
	if r == nil {
		return false
	}

	return errors.Is(err, context.DeadlineExceeded) || r.MatchString(err.Error())
}

func GetOptions(method string) *http.Options {
	options := http.NewOptioins().SetDebug(false)
	options.SetTimeout(time.Second * 10)

	return options
}
